package com.qdxwx.web.controller.order;

import com.qdxwx.common.json.AjaxResult;
import com.qdxwx.data.service.order.OrderService;
import com.qdxwx.data.service.website.WebsiteProfileService;
import com.qdxwx.models.enums.PayType;
import com.qdxwx.payment.alipay.AliPay;
import com.qdxwx.web.controller.BaseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author developer
 * 支付宝支付 controller
 */
@Controller
@RequestMapping("/order/alipay")
public class AlipayController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(AlipayController.class);

	@Autowired
	private OrderService orderService;

	@Autowired
	private WebsiteProfileService websiteProfileService;

	/**
	 * 支付宝回调 异步
	 */
	@RequestMapping("/notify.json")
	@ResponseBody
	public String alipayNotifyAsync(HttpServletRequest request) {
		AjaxResult result = alipayNotify(request);
		if (result.getCode() == 0) {
			return "success";
		} else {
			return "fail";
		}
	}

	/**
	 * 支付宝回调 2同步
	 */
	@RequestMapping("/return.html")
	public String alipayNotifySync(HttpServletRequest request, ModelMap mmap) {

		AjaxResult result = alipayNotify(request);
		if (result.getCode() == 0) {
			return "redirect:/order/pay/success.html?orderNo=" + result.get("data");
		} else {
			mmap.put("message", result.getMsg());
			return VIEW_ERROR;
		}
	}

	public AjaxResult alipayNotify(HttpServletRequest request) {
		try {
			// 支付宝返回数据的校验 最好是在异步做日志动作，可以记录mysign、sign、resposenTXT和其他值，方便以后查询错误。
			boolean checked = AliPay.getAlipayCheckInfo(request, websiteProfileService.getAlipay());
			if (!checked) {
				return AjaxResult.error("数据校验失败！");
			}
		} catch (Exception e) {
			return AjaxResult.error("程序执行错误：" + e.getMessage());
		}
		/* 可以在不同状态下获取订单信息，操作商户数据库使数据同步 */
		String outTradeNo = request.getParameter("trade_no"); // 支付宝交易号
		// 注意一定要返回给支付宝一个成功的信息(不包含HTML脚本语言)
		String tradeStatus = request.getParameter("trade_status");
		logger.info("trade_status = " + tradeStatus);
		if (tradeStatus.equals("TRADE_FINISHED") || tradeStatus.equals("TRADE_SUCCESS")) {
			// 校验好状态,在这里可以写入订单的数据处理,
			String orderNo = request.getParameter("out_trade_no");
			// 总价
			String totalFee = request.getParameter("total_fee");

			Map<String, Object> sourceMap = new HashMap<>();
			sourceMap.put("orderNo", orderNo);
			sourceMap.put("total_fee", totalFee);
			sourceMap.put("outTradeNo", outTradeNo);
			sourceMap.put("payType", PayType.ALIPAY.toString());
			// 必须校验支付的金额
			return orderService.updateCompleteOrder(request, sourceMap);
		} else if (tradeStatus.equals("WAIT_BUYER_PAY")) {
			// 等待买家付款
			return AjaxResult.error("等待买家付款！");

		} else {
			return AjaxResult.error("支付失败，Status：" + tradeStatus);
		}
	}
}
